package com.atguigu.gmall.pay.api;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.pay.service.PayService;
import com.atguigu.gmall.pay.vo.PayParamsVo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/api/payment")
public class PayController {

    @Autowired
    PayService payService;

    @Autowired
    OrderFeignClient orderFeignClient;


    /**
     * 查询订单交易状态  查询支付宝的订单是否支付了
     * 1:支付成功
     * 0:其他状态
     * @param outTradeNo
     * @return
     */
    @GetMapping("/status/{outTradeNo}")
    public String queryOrderPayStatus(@PathVariable("outTradeNo") String outTradeNo) throws JsonProcessingException, AlipayApiException {

       Boolean b = payService.queryOrderStatus(outTradeNo);

        return b?"1":"0";
    }

    /**
     * 收到来自于前端页面，点击扫码支付
     * @param orderId
     * @return
     * @throws Exception
     */
    //produces(生产)  产生什么数据 return payOrder 就是什么样的片段
    @GetMapping(value = "/alipay/submit/{orderId}",produces = "text/html")
    public String payment(@PathVariable("orderId") Long orderId) throws Exception {

        PayParamsVo payParamsVo = new PayParamsVo();
        OrderInfo orderById = orderFeignClient.getOrderById(orderId);
        payParamsVo.setTotal_amount(orderById.getTotalAmount().toString());
        payParamsVo.setOut_trade_no(orderById.getOutTradeNo());

        payParamsVo.setSubject(orderById.getConsignee()+"的订单");
        payParamsVo.setBody(orderById.getOrderComment());
        Date expireTime = orderById.getExpireTime();
        //简单日期格式    支付宝的自动收单，支付宝过期时间就是我们数据库中保存的订单过期时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        payParamsVo.setTime_expire(format.format(expireTime));
        //调用支付，返回支付页面
        String payOrder = payService.payOrder(payParamsVo);

        return payOrder;
    }
}
